<template>
  <div>
    <van-nav-bar
      :border="false"
      :title="$t('pageRobot.robot_setup')"
      left-arrow
      @click-left="$router.back()"
    />
    <van-form label-width="32%">
      <van-field
        :value="market"
        readonly
        clickable
        :label="$t('pageRobot.trade_area')"
        :placeholder="$t('pageRobot.trade_area')"
        :rules="[{ required: true }]"
        @click="onMarket"
      />
      <h3 class="title">预设策略</h3>
      <van-row class="preset">
        <van-col>
          <van-button
            block
            size="small"
            :type="preset === 1 ? 'primary' : 'default'"
            @click="changePreset(1)"
          >
            激进
          </van-button>
        </van-col>
        <van-col>
          <van-button
            block
            size="small"
            :type="preset === 2 ? 'primary' : 'default'"
            @click="changePreset(2)"
          >
            保守
          </van-button>
        </van-col>
        <van-col>
          <van-button
            block
            size="small"
            :type="preset === 3 ? 'primary' : 'default'"
            @click="changePreset(3)"
          >
            稳健
          </van-button>
        </van-col>
        <van-col>
          <van-button
            block
            size="small"
            :type="preset === 4 ? 'primary' : 'default'"
            @click="changePreset(4)"
          >
            自定义
          </van-button>
        </van-col>
      </van-row>
      <van-field
        v-model="first_order_value"
        :label="$t('first_order_amount') + '(' + money + ')'"
        :placeholder="$t('first_order_amount')"
        :rules="[{ required: true }]"
      />
      
      <van-field
        v-if="!max_order_count || max_order_count ==0 || (cover_num && max_order_count)"
        v-model="cover_num"
        :label="$t('cover_num')"
        :placeholder="$t('cover_num')"
      />
      <van-button
        v-if="!max_order_count || max_order_count ==0 || (cover_num && max_order_count)"
        block
        size="small"
        style="position: absolute;width: 50px;right: 16px;top:28%;z-index: 10;color: cornflowerblue"
        @click="setCoverNum()"
      >
        设置
      </van-button>

      <van-field
        v-if="!cover_num || cover_num ==0 || (cover_num && max_order_count)"
        v-model="max_order_count"
        :label="$t('number_of_orders')"
        :placeholder="$t('number_of_orders')"
      />

      <van-field
        v-if="!cover_num || cover_num ==0 || (cover_num && max_order_count)"
        v-model="cover_rate"
        :label="$t('cover_down') + '(%)'"
        :placeholder="$t('cover_down')"
      />
      <van-field
        v-model="cover_callback_rate"
        :label="$t('cover_pullback') + '(%)'"
        :placeholder="$t('cover_pullback')"
        :rules="[{ required: true }]"
      />
      <van-field
        v-model="stop_profit_rate"
        :label="$t('take_profit_ratio') + '(%)'"
        :placeholder="$t('take_profit_ratio')"
        :rules="[{ required: true }]"
      />
      <van-field
        v-model="stop_profit_callback_rate"
        :label="$t('take_profit_retracement') + '(%)'"
        :placeholder="$t('take_profit_retracement')"
        :rules="[{ required: true }]"
      />
      <van-field name="switch" :label="$t('is_fxkz')">
        <template #input>
          <van-switch :value="is_fxkz" size="16px" @input="onInput" v-model="is_fxkz"/>
        </template>
      </van-field>
      <van-field
        v-show="is_fxkz"
        v-model="buy_min"
        :label="$t('buy_min')"
        :placeholder="$t('buy_min')"
      />
      <van-field
        v-show="is_fxkz"
        v-model="buy_max"
        :label="$t('buy_max')"
        :placeholder="$t('buy_max')"
      />
      <!-- <van-field
        v-model="cover_number"
        :label="$t('cover_number')"
        :placeholder="$t('cover_number')"
      />
      <van-field
        v-model="stop_number"
        :label="$t('stop_number')"
        :placeholder="$t('stop_number')"
      /> -->
      <van-field name="radio" :label="$t('pageRobot.strategy_type')">
        <template #input>
          <van-radio-group v-model="recycle_status" direction="horizontal">
            <van-radio :name="1">{{ $t('cycle_strategy') }}</van-radio>
            <van-radio :name="0">{{ $t('single_strategy') }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>

      <van-field
        v-model="max_loop_num"
        :label="$t('max_loop_num')"
        :placeholder="$t('max_loop_num')"
        :rules="[{ required: true }]"
      />

      <van-field
        v-if="formType === 'create' && CHEKC_CDKEY"
        v-model="cd_key"
        :label="$t('cdkey')"
        :placeholder="$t('cdkey')"
        :rules="[{ required: true }]"
      />
      <div v-if="formType === 'create'" class="tips">
        {{ $t('tip') }}：{{ initInfo.quant_startup_min }} {{ initInfo.quant_revenue_type === '2' ? initInfo.system_balance_name : 'USDT' }}
      </div>
      <div style="padding: 16px;">
        <van-button round block type="info" @click="onSubmit">
          {{ $t('actions.submit') }}
        </van-button>
      </div>
    </van-form>
    <van-popup v-model="marketPicker" position="bottom">
      <van-picker
        show-toolbar
        :columns="marketLists"
        value-key="market_name"
        @confirm="onConfirm"
        @cancel="marketPicker = false"
      />
    </van-popup>

    <!-- 弹出层 -->
    <van-dialog v-model="showModal" title="补仓设置" show-cancel-button @confirm="buyCdkey">
      <div class="dialog-1">
        <table>
          <thead>
            <th>补仓次数</th>
            <th>补仓跌幅</th>
            <th>补仓倍数</th>
          </thead>
          <tbody>
            <!-- 循环渲染表格行 --> 
            <tr v-for="(item, index) in formItems" :key="index">
              <td style="width: 30%;text-align: center;padding: 10px;">
                第{{index+1}}补仓
              </td>
              <td>
                <input type="text" v-model="item.cover_rate" style="width: 70%;text-align: center;"/>%
              </td>
              <td>
                <input type="text" v-model="item.cover_multiple" style="width: 70%;text-align: center;"/>倍
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </van-dialog>


  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex'
import { CHEKC_CDKEY } from '@/config/index'
export default {
  i18n: {
    messages: {
      zh: {
        tip: '启动机器人最小余额'
      },
      en: {
        tip: 'Start robot minimum balance'
      }
    }
  },
  data() {
    return {
      CHEKC_CDKEY,
      preset: 4,
      formType: 'create',
      marketPicker: false,
      market: '',
      money: '',
      platform: '',
      robot_id: '',
      market_id: '',
      first_order_value: '100',
      max_order_count: '',
      stop_profit_rate: '',
      stop_profit_callback_rate: '',
      cover_rate: '',
      cover_callback_rate: '',
      recycle_status: '1',
      cd_key: '',
      cover_number:'',
      stop_number:'',
      cover_num:'',
      showModal:false,
      formItems: {},
      is_fxkz:0,
      checked:false,
      buy_min:'',
      buy_max:'',
      max_loop_num:''
    }
  },
  computed: {
    ...mapState({
      initInfo: index => index.initInfo,
      robotList: ({ robot }) => robot.robotList,
      thirdLoginEnabled: ({ thirdLoginEnabled }) => thirdLoginEnabled
    }),
    ...mapGetters({
      markets: 'robot/markets'
    }),
    marketLists() {
      return this.markets(this.platform) || []
    }
  },
  created() {
    this.formType = this.$route.query.type
    if (this.formType === 'edit') {
      const robot = (this.robot = this.robotList.find(
        item => this.$route.query.robot_id === item.id
      ))
      this.$nextTick(() => {
        this.platform = robot.platform
        this.market = robot.market_name
        this.market_id = robot.market_id
        this.robot_id = robot.id
        this.first_order_value = robot.first_order_value
        this.max_order_count = robot.max_order_count
        this.stop_profit_rate = robot.stop_profit_rate
        this.stop_profit_callback_rate = robot.stop_profit_callback_rate
        this.cover_rate = robot.cover_rate
        this.cover_callback_rate = robot.cover_callback_rate
        this.recycle_status = robot.recycle_status
        this.money = robot.money
        this.cover_number = robot.cover_number
        this.stop_number = robot.stop_number
        this.max_loop_num = robot.max_loop_num
        this.is_fxkz = robot.is_fxkz
        this.buy_min = robot.buy_min
        this.buy_max = robot.buy_max
        this.formItems = robot.cover_str
        this.cover_num = robot.cover_num
      })
    } else {
      const markets = JSON.parse(this.$route.query.data)
      this.platform = this.$route.query.platform
      this.market = markets.market_name
      this.market_id = markets.id
      this.money = markets.money
    }
    this.marketList({
      platform: this.platform,
      type: 'spot'
    })
  },
  methods: {
    ...mapActions({
      marketList: 'robot/marketList',
      robotCreate: 'robot/robotCreate',
      robotEdit: 'robot/robotEdit'
    }),
    onMarket() {
      if (this.formType === 'create') {
        this.marketPicker = true
      }
    },
    onSubmit() {
      if(!this.max_order_count && !this.cover_num){
        this.$toast('请设置做单次数或者补仓次数')
        return
      }

      if(this.max_order_count==0 && this.cover_num==0){
        this.$toast('请设置做单次数或者补仓次数')
        return
      }

      if(!this.max_order_count && this.cover_num <=0 ){
        this.$toast('请正确设置补仓次数')
        return
      }
      // console.log(this.formItems.length,111)
      if(this.cover_num>0 && this.formItems && !this.formItems.length){
        this.$toast('请填写补仓设置')
        return
      }
      // console.log(this.formItems)
      
      // console.log(is_has_empty)
      if (this.cover_num>0) {
        let is_has_empty = this.checkEmptyValues(this.formItems)
        if(is_has_empty){
          this.$toast('请填写补仓设置')
          return
        }
      }
      if(this.recycle_status == 1 && this.max_loop_num <=0){
        this.$toast('请设置循环次数')
        return
      }
      this.$toast.loading()
      const payload = {
        platform: this.platform,
        market_id: this.market_id,
        first_order_value: this.first_order_value,
        max_order_count: this.max_order_count,
        stop_profit_rate: this.stop_profit_rate,
        stop_profit_callback_rate: this.stop_profit_callback_rate,
        cover_rate: this.cover_rate,
        cover_callback_rate: this.cover_callback_rate,
        recycle_status: this.recycle_status,
        cd_key: this.cd_key,
        cover_number: this.cover_number,
        stop_number: this.stop_number,
        max_loop_num:this.max_loop_num ,
        is_fxkz:this.is_fxkz ,
        buy_min:this.buy_min ,
        buy_max:this.buy_max ,
        cover_str:this.formItems ,
        cover_num:this.cover_num,
      }
      if (this.formType === 'edit') {
        payload.robot_id = this.robot_id
      }
      const promise =
        this.formType === 'create' ? this.robotCreate(payload) : this.robotEdit(payload)
      promise
        .then((res) => {
          this.$toast(res.msg)
          this.$router.back()
        })
        .catch(({ msg }) => this.$toast(msg))
    },
    onConfirm(value) {
      this.market = value.market_name
      this.market_id = value.id
      this.marketPicker = false
    },
    setCoverNum(){
      if(this.cover_num <=0 || !this.cover_num){
        this.$toast('请设置补仓次数')
        return
      }
      if (this.formType === 'edit') {
        const robot = (this.robot = this.robotList.find(
          item => this.$route.query.robot_id === item.id
        ))
      // console.log(this.cover_num)
      // console.log(robot.cover_num)
        if( robot.cover_num != this.cover_num){
            if(this.formItems.length != this.cover_num){
              this.formItems = Array.from({ length: this.cover_num }, (_, i) => ({ // 创建5个表单项的数组
                cover_rate: '',
                cover_multiple: ''
              }))
            }
        }
      }else{
        if(this.formItems.length != this.cover_num){
          this.formItems = Array.from({ length: this.cover_num }, (_, i) => ({ // 创建5个表单项的数组
            cover_rate: '',
            cover_multiple: ''
          }))
        }
      }
      // console.log(this.cover_num)
      // console.log(this.formItems.length)
      // if(!this.formItems.length){
        
      // }
      this.showModal = true
    },
    buyCdkey(){
      console.log(this.formItems)
    },
    checkEmptyValues(arr) {
      // 遍历数组中的每个对象
      for (let i = 0; i < arr.length; i++) {
        const obj = arr[i];
        // 遍历对象的每个属性
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            const value = obj[key];
            // 根据你的定义检查空值
            if (value === null ||
                value === undefined ||
                value === '' ||
                value === 0 ||
                isNaN(value) ||
                value === false) {
              return true; // 如果找到空值，返回true
            }
          }
        }
      }
      return false; // 如果没有找到空值，返回false
    },
    onInput(is_fxkz) {
        this.is_fxkz = is_fxkz;
    },
    changePreset(index) {
      this.preset = index
      if (index === 1) {
        this.max_order_count = '6'
        this.stop_profit_rate = '1'
        this.stop_profit_callback_rate = '0.3'
        this.cover_rate = '1.8'
        this.cover_callback_rate = '0.3'
        this.max_loop_num = '10'
        this.cover_num = ''
        this.formItems = Array.from({ length: 6 }, (_, i) => ({ // 创建5个表单项的数组
          cover_rate: '',
          cover_multiple: ''
        }))
      } else if (index === 2) {
        this.max_order_count = '6'
        this.stop_profit_rate = '1.3'
        this.stop_profit_callback_rate = '0.3'
        this.cover_rate = '1.5'
        this.cover_callback_rate = '0.3'
        this.max_loop_num = '10'
        this.cover_num = ''
        this.formItems = Array.from({ length: 6 }, (_, i) => ({ // 创建5个表单项的数组
          cover_rate: '',
          cover_multiple: ''
        }))
      } else if (index === 3) {
        this.max_order_count = '6'
        this.stop_profit_rate = '1.5'
        this.stop_profit_callback_rate = '0.3'
        this.cover_rate = '2'
        this.cover_callback_rate = '0.5'
        this.max_loop_num = '10'
        this.cover_num = ''
        this.formItems = Array.from({ length: 6 }, (_, i) => ({ // 创建5个表单项的数组
          cover_rate: '',
          cover_multiple: ''
        }))
      } else if (index === 4) {
        if (this.formType === 'edit') {
          const robot = (this.robot = this.robotList.find(
            item => this.$route.query.robot_id === item.id
          ))
          this.$nextTick(() => {
            this.platform = robot.platform
            this.market = robot.market_name
            this.market_id = robot.market_id
            this.robot_id = robot.id
            this.first_order_value = robot.first_order_value
            this.max_order_count = robot.max_order_count
            this.stop_profit_rate = robot.stop_profit_rate
            this.stop_profit_callback_rate = robot.stop_profit_callback_rate
            this.cover_rate = robot.cover_rate
            this.cover_callback_rate = robot.cover_callback_rate
            this.recycle_status = robot.recycle_status
            this.money = robot.money
            this.cover_number = robot.cover_number
            this.stop_number = robot.stop_number
            this.max_loop_num = robot.max_loop_num
            this.is_fxkz = robot.is_fxkz
            this.buy_min = robot.buy_min
            this.buy_max = robot.buy_max
            this.formItems = robot.cover_str
            this.cover_num = robot.cover_num
          })
         
        }else{
          this.max_order_count = ''
          this.stop_profit_rate = ''
          this.stop_profit_callback_rate = ''
          this.cover_rate = ''
          this.cover_callback_rate = ''
          this.max_loop_num = ''
          this.cover_num = ''
          this.formItems = {}
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.title {
  padding: 10px 15px;
  font-size: 14px;line-height: 1;
}
.preset {
  padding: 0 10px 10px;
  display: flex;
  justify-content: space-around;
  .van-col {
    flex: 1;
    margin: 0 5px;
  }
}
.tips {
  padding: 10px 15px;
  font-size: 12px;
}
.dialog-1 {
  padding: 20px 10px;
  .van-cell__value {
    display: flex;align-items: center;
  }
  .label {
    width: 5em;
    flex-shrink: 0;
  }
  input {
    border: none;
    flex-grow: 1;
    min-width: 0;
  }
  .tip {
    text-align: right;
    padding: 10px 16px;
    font-size: 12px;
    span {
      color: blue;
    }
  }
}
</style>
